package com.hou.houlymall.ware.service.impl;

import com.hou.common.constant.WareConstant;
import com.hou.houlymall.ware.service.WareSkuService;
import com.hou.houlymall.ware.vo.MergeVo;
import com.hou.houlymall.ware.entity.PurchaseDetailEntity;
import com.hou.houlymall.ware.service.PurchaseDetailService;
import com.hou.houlymall.ware.vo.PurchaseDoneVo;
import com.hou.houlymall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hou.common.utils.PageUtils;
import com.hou.common.utils.Query;

import com.hou.houlymall.ware.dao.PurchaseDao;
import com.hou.houlymall.ware.entity.PurchaseEntity;
import com.hou.houlymall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author Hou
 */
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService detailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 表名称：wms_purchase
     * 获取未被领取的采购单
     * @param params 分页参数
     * @return 查询分页结果
     */
    @Override
    public PageUtils queryPageUnaccalimedPurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    /**
     * 表名称：wms_purchase
     * 采购需求合并到采购单，其实就是设置 wms_purchase_detail 表中的 purchase_id 值
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId == null){
            //1、如果没有选择采购单新建一个
            PurchaseEntity purchaseEntity = new PurchaseEntity();

            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }



        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            return detailService.getById(i);
        }).filter(item -> {
            //确认采购单状态是0或1才可以合并
            return item.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode();
        }).peek(item -> {
            item.setPurchaseId(finalPurchaseId);
            item.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
        }).collect(Collectors.toList());
        detailService.updateBatchById(collect);

        //更新 wms_purchase 中采购单的更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     *
     * @param ids 采购单id
     */
    @Override
    public void received(List<Long> ids) {
        //1、确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            //根据采购单id获取采购单
            return this.getById(id);
        }).filter(item -> {
            //判断采购单状态（true 放行）
            return item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).map(item->{
            //设置采购单最新状态
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //2、批量修改采购单的状态
        this.updateBatchById(collect);

        //3、改变采购需求的状态
        collect.forEach((item)->{
            //根据采购单id获取他下面所有采购需求
            List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(item.getId());
            //批量修改采购需求的状态
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
                PurchaseDetailEntity entity1 = new PurchaseDetailEntity();
                entity1.setId(entity.getId());
                entity1.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return entity1;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntities);
        });
    }

    /**
     * 完成采购
     * @param doneVo ...
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public void done(PurchaseDoneVo doneVo) {

        Long id = doneVo.getId();


        //1、改变采购需求的状态
        boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();

        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ABNORMAL.getCode()){
                flag = false;
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ABNORMAL.getCode());
            }else{
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3、将成功采购的进行入库
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        detailService.updateBatchById(updates);

        //2、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        //只要采购需求中出现过一例采购失败，则采购单归为采购失败
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.ABNORMAL.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}